/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
  // 1.未优化
  // let value = new Array(nums.length);
  // value[0] = nums[0];
  // for(let i = 1; i < nums.length; i++) {
  //   // 当前的值，max(当前的数组值，上一个数组的值加上这个值)
  //   value[i] = Math.max(nums[i], value[i - 1] + nums[i]);
  // }
  // return Math.max(...value);
  // 2.优化代码
  if(nums.length == 1)
    return nums[0];
  let oldValue = nums[0], newValue, maxValue = nums[0];
  for(let i = 1; i < nums.length; i++) {
    newValue = Math.max(nums[i], oldValue + nums[i]);
    oldValue = newValue;
    if(newValue > maxValue)
      maxValue = newValue;
  }
  return maxValue;
};

let nums = [-2,1,-3,4,-1,2,1,-5,4];
console.log(maxSubArray(nums));
nums = [1];
console.log(maxSubArray(nums));
nums = [5,4,-1,7,8];
console.log(maxSubArray(nums));
nums = [-1, -2];
console.log(maxSubArray(nums));
